package com.coolw.data.migrate.common.listener;

import com.coolw.data.migrate.common.listener.event.BaseEvent;
import com.coolw.data.migrate.domain.response.DataMigrateResponse;
import com.coolw.data.migrate.entity.DataMigrateLogEntity;
import com.coolw.data.migrate.enums.MigrateStatusEnum;
import com.coolw.data.migrate.service.DataMigrateLogService;
import lombok.extern.slf4j.Slf4j;
import org.dromara.hutool.core.data.id.IdUtil;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.concurrent.ExecutorService;

/**
 * 数据迁移监听器,监听DataMigrateEvent事件
 *
 * @author coolw
 * @date 2024/2/21 11:18
 */
@Slf4j
@Component
public class DataMigrateListener {

    @Resource
    private ExecutorService dataMigrateExecutorService;

    @Resource
    private DataMigrateLogService dataMigrateLogService;

    @EventListener
    public void handleEvent(BaseEvent<DataMigrateResponse> event) {
        DataMigrateResponse data = event.getEventData();
        if (Objects.isNull(data)) {
            log.warn("eventData为空");
            return;
        }

        DataMigrateLogEntity logEntity = new DataMigrateLogEntity();
        logEntity.setMigrateLogNo(IdUtil.getSnowflakeNextId());
        logEntity.setSourceTableName(data.getSourceTableName());
        logEntity.setTargetTableName(data.getTargetTableName());
        logEntity.setTotalSize(data.getTotalSize());
        logEntity.setSuccessSize(data.getSuccessSize());
        logEntity.setFailSize(data.getFailSize());
        logEntity.setCost(data.getCost());
        logEntity.setRemark(data.getMessage());
        logEntity.setReqParam(event.getReqParam());
        if (data.getSuccess()) {
            if (Objects.equals(data.getTotalSize(), data.getSuccessSize())) {
                logEntity.setStatus(MigrateStatusEnum.SUCCESS.getCode());
            } else {
                logEntity.setStatus(MigrateStatusEnum.PART_SUCCESS.getCode());
            }
        } else {
            logEntity.setStatus(MigrateStatusEnum.FAIL.getCode());
        }
        if (data.getAlarmStatusEnum() != null) {
            logEntity.setAlarmStatus(data.getAlarmStatusEnum().getCode());
        }

        dataMigrateExecutorService.execute(() -> dataMigrateLogService.save(logEntity));
    }
}
